package com.itheima.security;

import com.itheima.pojo.User;
import com.qiniu.util.Md5;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Component     <context:component-scan base-package="com.itheima.security"></context:component-scan>
public class MyUserService implements UserDetailsService {

    //模拟数据库中的用户数据
    public Map<String, User> map = new HashMap<>();

    public void initData(){
        com.itheima.pojo.User user1 = new com.itheima.pojo.User();
        user1.setUsername("admin");
        user1.setPassword("$2a$10$Ydz0oCZJz2VIPxLO4uKe2OLbLdsREQP6gc5paYJixIKbgfkZSiF6G");

        com.itheima.pojo.User user2 = new com.itheima.pojo.User();
        user2.setUsername("xiaoming");
        user2.setPassword("$2a$10$Ydz0oCZJz2VIPxLO4uKe2OLbLdsREQP6gc5paYJixIKbgfkZSiF6G");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }
    /**
     *
     * @param username 就是登录时输入的用户
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initData();
        //根据用户名查询用户基本信息（id，密码）
        User user = map.get(username);
        if(null == user){
            return null;
        }
        //根据用户id查询用户拥有的权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if(username.equals("admin")){
            authorities.add(new SimpleGrantedAuthority("checkitem_delete"));
        }
        authorities.add(new SimpleGrantedAuthority("checkitem_add"));

        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
    }

    public static void main(String[] args) {
        String pwd = "1234";
        long md5s = System.currentTimeMillis();
        String s = Md5.md5(pwd.getBytes());
        System.out.println(System.currentTimeMillis() - md5s);


        long encoders = System.currentTimeMillis();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(pwd);
        System.out.println(encode);

        //$2a$10$QQWluecZC5cnAqqPHVsmguXDkyhO8QcnlHudN/dauDzKduBnSSr5i
        boolean boo = encoder.matches(pwd, "$2a$10$WyQlt8ZvQQUGn2PN10jQIOEU4pkMsgKN70vurVyXi3N7ThzEUBsru");

        System.out.println(boo);

//        System.out.println(System.currentTimeMillis() - encoders);
    }
}
